package org.apach.server;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

/** 
 * @Description: TODO 处理请求和响应
 * @author JH   
 * @date 2014-4-11 下午10:13:03    
 */
public class HttpProcess {
	
	private InputStream in;
	private PrintStream out;
	public final static String WEB_ROOT = System.getProperty("user.dir") + File.separator + "WebRoot";
	
	public HttpProcess(Socket socket){
		try {
			in = socket.getInputStream();
			out = new PrintStream(socket.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void process(){
		sendFile(parse(in));
	}
	
	/**
	 * 输出文件内容
	 * @param fileName
	 */
	private void sendFile(String fileName){
		try {
			File file = new File(HttpProcess.WEB_ROOT + fileName);
			if(file.exists()){
				InputStream in = new FileInputStream(file);
				byte content[] = new byte[(int)file.length()];
				in.read(content);
				out.println("HTTP/1.0 200 Query File");
				out.println("content-length:"+ content.length + "\r\n");
				out.write(content);
				close();
			}else{
				returnMessage(404, "File Not Found");
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取输入的文件
	 * @param in
	 * @return
	 */
	private String parse(InputStream in){
		BufferedReader br = new BufferedReader(new InputStreamReader(in));
		String fileName = null;
		try {
			String httpMessage = br.readLine();
			if(httpMessage == null){
				return null;
			}
			String[] content = httpMessage.split(" ");
			if(content == null || content.length != 3){
				returnMessage(400, "Client request error!");
				return null;
			}
			fileName = content[1];
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileName;
	}
	
	/**
	 * 返回对应状态信息
	 * @param code
	 * @param message
	 */
	private void returnMessage(int code, String message){
		StringBuffer sb = new StringBuffer();
		sb.append("HTTP/1.0 " + code + " " + message +"\r\n");
		sb.append("Content-Type: text/html\r\n");
		sb.append("Content-Length: 23\r\n");
		sb.append(message);
		try {
			out.write(sb.toString().getBytes());
			close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 关闭流
	 */
	private void close(){
		try {
			if(out != null){
				out.flush();
				out.close();
			}
			if(in != null){
				in.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
